package log;

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBWorker {
	
	private Connection conection;
	

	public Connection getConnection() {
		return conection;
	}

	public void setConnection(Connection conection) {
		this.conection = conection;
	}
	//метод для зручного виводу помилок
	public void exept(SQLException ex){
 	   System.out.println("SQLException caught");
       System.out.println("---");
       while ( ex != null ){
    	   System.out.println("Message   : " + ex.getMessage());
    	   System.out.println("SQLState  : " + ex.getSQLState());
    	   System.out.println("ErrorCode : " + ex.getErrorCode());
    	   System.out.println("---");
    	   ex = ex.getNextException();
       }
	}
	//створюєм з’єднання по замовчеванню
	public DBWorker(){
						
		setConnection(null) ;
		try {
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			setConnection((Connection) DriverManager.getConnection("jdbc:mysql://localhost/dblogs", "root", ""));
	       	} 
	       	catch (SQLException ex)
	       	{
	       		exept(ex);	
	        }
	       
		
	}
	
	public DBWorker(String db, String login, String password){
		
		setConnection(null) ;
		try {
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			setConnection((Connection) DriverManager.getConnection("jdbc:mysql://localhost/" + db, login, password));
	       	} 
	       	catch (SQLException ex)
	       	{
	       		exept(ex);	
	       	}
	}
	/*jdbc:mysql://localhost/dblogs", "root", ""
	 * dblogs - назваа таблиці!
	 * 
	 * */
	public void log(int id, String file, boolean result){
		try {
		   	Statement s = (Statement) getConnection().createStatement() ;
		   	((java.sql.Statement) s).executeUpdate("INSERT INTO `logs` (`id`, `file`, `result`, `time`) VALUES ("+id+", "+file+", "+result+", now());");
			} 
			catch (SQLException ex)
			{
	       		exept(ex);	
	      	}
	}

}